import { useState, useEffect } from 'react'

const useFetch = (url) => {
  const [ isPending, setIsPending ] = useState(true)
  const [ error, setError ] = useState(null)
  const [ data, setData ] = useState(null)
  const abortController = new AbortController()
  useEffect(() => {
    fetch(url, {signal: abortController.signal})
    .then(res => {
      if (!res.ok) throw new Error('获取数据失败')
      return res.blob()
    })
    .then(res => {
      const ret = URL.createObjectURL(res)
      setData(ret)
    })
    .catch(err => {
      // if (err.name === 'ab')
      setError(err.message)
    })
    .finally(() => {
      setIsPending(false)
    })
    return () => {
      abortController.abort()
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url])

  return {
    isPending,
    error,
    data
  }
}

export default useFetch